package com.project.dhCamera.controller;

import com.project.dhCamera.entity.MonitorVo;
import com.project.dhCamera.service.FFmpegManager;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author Sweey Zhang
 * @description
 * @date 2021/7/16 15:37
 */
@RestController
public class DhCameraController {
    @Autowired
    public FFmpegManager manager;

    /**
     * @return
     * @Description 抓图
     * @Date 2021/7/16 10:14
     */
    @PostMapping("/monitor/start")
    public void capturePicture(@RequestBody MonitorVo monitorVo) {
        ExecutorService pool = new ThreadPoolExecutor(8, 10, 30, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        pool.submit(new MonitorRunnable(monitorVo));
    }

    class MonitorRunnable implements Runnable {

        private MonitorVo monitorVo;

        MonitorRunnable(MonitorVo monitorVo) {
            this.monitorVo = monitorVo;
        }

        @Override
        public void run() {
            if (monitorVo != null && monitorVo.getAppName() != null) {
                String appName = monitorVo.getAppName();
                String ip = monitorVo.getIp();
                try {
                    Map<String, String> map = new HashMap<>();
                    map.put("appName", appName);//code为客户端编码
//            map.put("input", "\"rtsp://username:password@" + ip + 端口"/cam/realmonitor?channel=1&subtype=0\"");
                    map.put("input", "rtsp://admin:YBGX1234@117.172.167.248:38888/cam/realmonitor?channel=1&subtype=0");
                    map.put("output", "rtmp://localhost:1935/live/");
                    map.put("codec", "h264");
                    map.put("fmt", "flv");
                    map.put("fps", "25");
                    map.put("rs", "640x360");
                    map.put("twoPart", "0");

                    //执行任务，id就是appName，如果执行失败返回为null
                    String id = manager.start(map);
                    // 将转流放入静态map中用于关转流
//            maps.put(code+ip,id);
                    //  manager.stop(id);
                    System.out.println(appName + ip + "流已开启");
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("启动失败");
                }
            }
        }
    }

    @GetMapping("/monitor/stop")
    public void stop(@Param("appName") String appName) {
        manager.stop(appName);
    }

    @GetMapping("/monitor/stopAll")
    public void stopAll() {
        manager.stopAll();
    }

    @GetMapping("/start")
    public void start() {
        int flag = -1;
        String rtspUrl = "rtsp://admin:YBGX1234@117.172.167.248:38888//cam/realmonitor?channel=1&subtype=0";
        String nginxRtmpUrl = "rtmp://localhost/live/rtmpStream";
        try {
            // ffmpeg 已经在系统环境变量中配置好了
            String command = "ffmpeg -rtsp_transport tcp ";
            command += " -i \"" + rtspUrl + "\"";
            command += " -vcodec copy -acodec copy -f flv -s 800x600 " + nginxRtmpUrl;
            System.out.println("ffmpeg推流命令：" + command);

            Process process = Runtime.getRuntime().exec(command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line = "";
            while ((line = br.readLine()) != null) {
                System.out.println("视频推流信息[" + line + "]");
            }
            flag = process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/test/{id}")
    public Map test(@PathVariable("id") Integer id) {
        Map<String, Object> map = new HashMap<>();
        try {
            TimeUnit.SECONDS.sleep(5);
            System.out.println("sleep 5s");
            if ("1".equals(String.valueOf(id))) {
                map.put("code", 200);
                map.put("message", "成功");
            } else {
                map.put("code", 400);
                map.put("message", "失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return map;
    }
}
